package cfca.payment.socket;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;

import org.apache.log4j.Logger;
import org.w3c.dom.Document;

import cfca.payment.system.TxDirectMessenger;
import payment.api.system.TxMessenger;
import payment.tools.net.NameValuePair;
import payment.tools.util.XmlUtil;

public class ChildThread  implements Runnable {

	private Socket socket  ; 
	
	Logger logger = Logger.getLogger(ChildThread.class.getName());
	
//	private String tname;
	public ChildThread(Socket socket){
	  this.socket=socket ;
	 }
	
	

	@Override
	public void run() {
//		logger.info("task " + tname + ":start");
		try {

			PropertiesUtil propertiesUtil = new PropertiesUtil();
			
//			Socket socket = serversocket.accept();
			String ip = socket.getInetAddress().getHostAddress();
			int port = socket.getLocalPort();
			logger.info("user [ " + ip + ":" + port + " ]");

			InputStream is = socket.getInputStream();
			OutputStream os = socket.getOutputStream();

			byte[] recData = new byte[100000];

			is.read(recData);// 接收
			String message = new String(recData, "UTF-8");
//			BufferedReader br = new BufferedReader(new InputStreamReader(is));
//			String message = null ;
//			while(!((message=br.readLine())==null)){
//				System.out.println("我是服务器请求信息为:"+message);
//			}
			logger.info(message.trim());

			// ------------------------------------------------------------------------------------------------
			Document doc = XmlUtil.createDocument(message.trim());
			// 获取交易码，判断同步异步
			String txCode = doc.getElementsByTagName("TxCode").item(0).getTextContent();
			logger.debug("交易码:" + txCode);
			// 报文处理成 明文和密文
			TxBaseRequest baseRequest = new TxBaseRequest();
			baseRequest.postProcess(doc);
			String requestMessage = baseRequest.getRequestMessage(); // 明文
			String requestSignature = baseRequest.getRequestSignature(); // 密文

			// 消息发送处理

			String txURL = null;
			String reply = null;
			if("1111".equals(txCode)||"1112".equals(txCode)
					||"1311".equals(txCode)||"1312".equals(txCode))
			{
				txURL = propertiesUtil.readValue("paymentURL").trim();
				logger.debug("txURL:" + txURL);
				TxDirectMessenger tx = new TxDirectMessenger();
			    ArrayList<NameValuePair> localArrayList = new ArrayList<NameValuePair>();
			    NameValuePair localNameValuePair1 = new NameValuePair("message", requestMessage);
			    NameValuePair localNameValuePair2 = new NameValuePair("signature", requestSignature);
			    localArrayList.add(localNameValuePair1);
			    localArrayList.add(localNameValuePair2);
			    // 直接取返回的form，透传给交易系统的浏览器
			    reply = tx.send(localArrayList, txURL);
			}
			else
			{
				txURL = propertiesUtil.readValue("txURL").trim();
				logger.debug("txURL:" + txURL);
				TxMessenger tx = new TxMessenger();
				String[] respMsg = null;
				respMsg = tx.send(requestMessage,
						requestSignature, txURL);// 0:message;
				// 1:signature
				String plainText = new String(
						payment.tools.util.Base64.decode(respMsg[0]),
						"UTF-8");
				
				logger.info("[message]=[" + respMsg[0] + "]");
				logger.info("[signature]=[" + respMsg[1] + "]");
				logger.info("[plainText]=[" + plainText + "]");
				reply = plainText;
			}

			// ------------------------------------------------------------------------------------------------

			logger.info("response:" + reply);
			os.write(reply.getBytes("UTF-8"));
			os.flush();

			socket.shutdownInput();

			// br.close();
			os.close();
			is.close();
			socket.close();
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e);
		}
	}



	public Socket getSocket() {
		return socket;
	}

	public void setSocket(Socket socket) {
		this.socket = socket;
	}


	
	
}
